//
//  LGInspectChartView.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/6/30.
//

#import "LGInspectChartView.h"
#import "LGInspectChartItemCell.h"
#import "LGScrollView.h"

#define topMargin     viewPix(57)

#define leftMargin    viewPix(37)+iPadMargin(10)

#define lineHeight    roundf((scrollHeight-viewPix(16))/self.yAxisArray.count)

#define scrollWidth    (Screen_W - viewPix(83))

#define scrollHeight   viewPix(200)

@interface LGInspectChartView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
/**   */
@property (nonatomic , strong)UILabel *titleLabel;
/**   */
@property (nonatomic , strong)UIView *baseView;
/**   */
@property (nonatomic , strong)UICollectionView *collectionView;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**   */
@property (nonatomic , strong)NSArray *yAxisArray;
/**   */
@property (nonatomic , strong)NSArray *dayArray;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
/**   */
@property (nonatomic , assign)CGFloat minValue;
/**   */
@property (nonatomic , assign)CGFloat maxValue;
/**   */
@property (nonatomic , assign)NSInteger index;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , strong)NSMutableArray *cacheArray;

@end

@implementation LGInspectChartView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.index = 0;
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
    }
    return self;
}

-(void)setTitle:(NSString *)title{
    _title = title;
    self.titleLabel.text = title;
}

-(void)setUnit:(NSString *)unit{
    _unit = unit;
    self.unitLabel.text = unit;
}

-(void)setItemArray:(NSArray *)itemArray{
    if(_itemArray && _itemArray.count>0) return;
    _itemArray = itemArray;
    [self.collectionView reloadData];
}

-(void)setChartDic:(NSDictionary *)chartDic{
    _chartDic = chartDic;
    [self.emptyView stopBufferAction];
    //清空数值
    for (NSInteger i=0; i<self.cacheArray.count; i++) {
        UIView *view = self.cacheArray[i];
        [view removeFromSuperview];
    }
    [self.cacheArray removeAllObjects];
    if(chartDic.allKeys.count>0){
        //画线
        self.totalCount = [chartDic[@"xAxis"] count];
        self.yAxisArray = chartDic[@"yAxis"];
        self.dayArray = chartDic[@"xAxis"];
        self.dataArray = chartDic[@"series"];
        self.scrollView.contentSize = CGSizeMake(self.itemWidth*self.totalCount+viewPix(20), scrollHeight);
    }
}

-(void)setYAxisArray:(NSArray *)yAxisArray{
    _yAxisArray = yAxisArray;
    self.minValue = [[yAxisArray firstObject] floatValue];
    self.maxValue = [[yAxisArray lastObject] floatValue];
    for (NSInteger i=0; i<yAxisArray.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:LGNSString(yAxisArray[yAxisArray.count-1-i]) colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+lineHeight*i, leftMargin, lineHeight);
        [self.baseView addSubview:label];
        [self.cacheArray addObject:label];
        //虚线
        CGFloat width = self.itemWidth*self.totalCount;
        width = (width>Screen_W)?width:Screen_W;
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, width+viewPix(20), lineHeight)];
        [self.scrollView addSubview:lineView];
        [self.cacheArray addObject:lineView];
    }
}



//创建X轴坐标
-(void)setDayArray:(NSArray *)dayArray{
    _dayArray = dayArray;
    for (NSInteger i=0; i<dayArray.count; i++) {
        UILabel *dayLabel = [UILabel lableWithText:dayArray[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, scrollHeight-viewPix(36), self.itemWidth, viewPix(36));
        dayLabel.tag = 1000+i;
        [self.scrollView addSubview:dayLabel];
        [self.cacheArray addObject:dayLabel];
    }
}

-(void)setDataArray:(NSArray *)dataArray{
    _dataArray = dataArray;
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSInteger i=0; i<dataArray.count; i++) {
        NSString *value = LGNSString(dataArray[i][@"value"]);
        NSString *status = LGNSString(dataArray[i][@"status"]);
        CGFloat pointY = (1-([value floatValue] - self.minValue)/(self.maxValue - self.minValue))*lineHeight*(self.yAxisArray.count-1)+lineHeight/2.0;
        NSDictionary *picName = @{@"up":@"异常指标-偏高",@"down":@"异常指标-偏低"};
        NSString *nameString = (status.length>0)?picName[status]:@"异常指标-正常";
        UIButton *button = [UIButton buttonWithImage:nameString selectImage:nameString];
        button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
        button.tag = 2000+i;
        [self.scrollView addSubview:button];
        [self.cacheArray addObject:button];
        UILabel *valueLabel = [UILabel lableWithText:value colorString:@"#000000" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        valueLabel.tag = 3000+i;
        [self.scrollView addSubview:valueLabel];
        [self.cacheArray addObject:valueLabel];
        [valueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(button.mas_top);
            make.centerX.equalTo(button);
        }];
        if([status isEqualToString:@"up"]){
            valueLabel.textColor = [UIColor colorWithString:@"#DB453A"];
        }else{
            valueLabel.textColor = [UIColor colorWithString:@"#000000"];
        }
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
    [self drawCurveLine:pointArray lineColor:@"#429BFF"];
}

//画线
-(void)drawCurveLine:(NSArray *)arry lineColor:(NSString *)color{
    if(arry.count == 0) return;
    CGPoint startPoint = [[arry objectAtIndex:0] CGPointValue];
    CGPoint lastPoint;
    UIBezierPath *lineBeizer = [UIBezierPath bezierPath];
    [lineBeizer setLineWidth:2.0];
    [lineBeizer moveToPoint:startPoint];

    for (NSInteger i = 0;i < arry.count;i++ ) {
        if (i <arry.count-1 ) {
            CGPoint nowPoint = [[arry objectAtIndex:i] CGPointValue];
            CGPoint futPoint  = [[arry objectAtIndex:i+1] CGPointValue];
            [lineBeizer addCurveToPoint:futPoint controlPoint1:CGPointMake((nowPoint.x+futPoint.x)/2, nowPoint.y) controlPoint2:CGPointMake((nowPoint.x+futPoint.x)/2, futPoint.y)];
            if (i == arry.count-2) {
                [lineBeizer moveToPoint:futPoint];//添加连线
                lastPoint = futPoint;
            }
        }
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = lineBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithString:color].CGColor;
    shapeLayer.lineWidth = 2.0;
    [self.scrollView.layer addSublayer:shapeLayer];
    for(NSInteger i=0; i<arry.count; i++){
        UIButton *button = [self viewWithTag:2000+i];
        UILabel *valueLabel = [self viewWithTag:3000+i];
        [self.scrollView bringSubviewToFront:button];
        [self.scrollView bringSubviewToFront:valueLabel];
    }
}



#pragma mark
#pragma mark ====> collectionViewDelegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.itemArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LGInspectChartItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.dataDic = self.itemArray[indexPath.item];
    cell.isSelected = (indexPath.item == self.index)?YES:NO;
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.index = indexPath.item;
    [self.collectionView reloadData];
    if(self.selectItemChnaged){
        self.selectItemChnaged(LGNSString(self.itemArray[indexPath.item][@"code"]));
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *tempDic = self.itemArray[indexPath.item];
    NSString *content = LGNSString(self.itemArray[indexPath.item][@"title"]);
    CGFloat width = [content textWidthWithFont:LGFontWeight(12, UIFontWeightMedium) maxHeight:MAXFLOAT];
    return CGSizeMake(width+viewPix(24), viewPix(50));
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, viewPix(8), 0, viewPix(8));
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    [self addSubview:self.titleLabel];
    [self addSubview:self.baseView];
    [self.baseView addSubview:self.collectionView];
    [self.baseView addSubview:self.scrollView];
    [self.baseView addSubview:self.unitLabel];
    [self.baseView addSubview:self.emptyView];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self).offset(viewPix(16));
        make.right.equalTo(self).offset(-viewPix(16));
    }];
}


-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"变化趋势" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:2];
    }
    return _titleLabel;
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [UIView shadowViewWithColor:@"#B2BDC7" offset:CGSizeMake(0, 2) opacity:0.15 radius:15];
        _baseView.frame = CGRectMake(viewPix(16), viewPix(50), Screen_W-viewPix(32), viewPix(257));
        _baseView.backgroundColor = [UIColor whiteColor];
    }
    return _baseView;
}

-(UICollectionView *)collectionView{
    if(!_collectionView){
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumInteritemSpacing = viewPix(4);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, Screen_W-viewPix(32), viewPix(50)) collectionViewLayout:layout];
        [_collectionView registerClass:[LGInspectChartItemCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@"" colorString:@"#666666" textFont:LGFont(12) textAlignment:NSTextAlignmentLeft lines:1];
        _unitLabel.frame = CGRectMake(viewPix(12), topMargin-8, 200, viewPix(17));
    }
    return _unitLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

-(LGEmptyView *)emptyView{
    if(!_emptyView){
        _emptyView = [[LGEmptyView alloc] initWithFrame:CGRectMake(0, viewPix(50), Screen_W-viewPix(32), viewPix(207))];
        _emptyView.backgroundColor = [UIColor whiteColor];
        _emptyView.cornerRidus = 15;
        _emptyView.margin = -viewPix(15);
        _emptyView.hidden = YES;
    }
    return _emptyView;
}



@end
